import { lazy, useEffect, useState } from 'react'
import { HeartOutline, MessageOutline } from 'antd-mobile-icons'
import img1 from '../../../imgae/红心.png'
import { Skeleton } from 'antd-mobile'
import {
    postAddComment, postAddReply,
    postgetcomments, postAddthree, postAddlike
} from '../../../api/csy/api'

import { format } from "date-fns";
import { List } from 'antd-mobile'
import { Comment, ListProps, SingularProps } from '../type/singular'

const Singular = ({ list, getdata }: any) => {


    const [singular, setSingular] = useState('');  // 用于存储评论内容
    const [comments, setComments] = useState<Comment[]>([]);  // 用于存储评论列表
    const [loading, setLoading] = useState(false);  // 加载状态
    const user = localStorage.getItem('_id');  // 获取当前用户的ID
    const [name, setName] = useState("")  // 回复评论的用户名字
    const [target, setTarget] = useState()  // 回复评论的用户ID
    const [three, setThree] = useState([])  // 回复三级评论

    function generateRandomHex() {
        const array = new Uint8Array(12); // 12字节
        crypto.getRandomValues(array); // 填充数组
        return Array.from(array, byte => byte.toString(16).padStart(2, '0')).join('');
    }



    //提交评论
    const dian = async (e: React.KeyboardEvent<HTMLInputElement>) => {
        if (e.keyCode === 13 && singular.trim()) {  // 按下回车键提交评论
            setLoading(true);
            try {
                if (name === '' && three) {
                    // 提交评论
                    await postAddComment({
                        user: user,
                        article: list.id,
                        content: singular,
                        callId: generateRandomHex(),  // 生成评论的 callId
                    });
                } else if (three == undefined) {
                    await postAddthree({
                        user: user,
                        content: singular,
                        target_callId: target,
                    })

                } else {
                    // 提交二级回复
                    await postAddReply({
                        user: user,
                        self_callId: generateRandomHex(),  // 为每个回复生成一个新的 callId
                        target_callId: target,
                        content: singular,
                    });
                }
                setSingular('');  // 清空输入框
                getpl();  // 提交评论后重新获取评论列表
            } catch (error) {
                console.error("Failed to add comment or reply:", error);
            } finally {
                setLoading(false);  // 隐藏加载状态
            }
        }
    };


    // 获取评论列表
    const getpl = async () => {
        if (list?.id) {
            setLoading(true);  // 获取评论时显示加载状态
            try {
                const res = await postgetcomments({ article: list.id });
                // 检查返回的数据是否是数组
                if (Array.isArray(res.data.data)) {
                    setComments(res.data.data);  // 设置评论数据
                } else {
                    setComments([]);  // 如果不是数组，设置为空数组
                }
            } catch (error) {
                console.error("Failed to fetch comments:", error);

            } finally {
                setLoading(false);  // 隐藏加载状态
            }
        }
    };

    // 在组件加载时调用 getpl 获取评论
    useEffect(() => {
        getpl();
    }, [list?.id]);  // 依赖 List.id，List.id 变化时重新获取评论

    const goback = (e: any) => {
        console.log(e);
        setName(e.user.phone)
        setTarget(e._id)
        setThree(e.article)
    }



    const renderReplies = (replies: any[]) => {
        return replies && replies.length > 0 ? replies.map(reply => (
            <div key={reply._id} className="reply-item">
                <span className="comment-author">{reply.user.phone}</span>
                <div className="comment-content">
                    <span>{reply.content}</span>
                </div>
                <span className="comment-time">{format(reply.time, 'yyyy-MM-dd HH:mm ')}</span>
                <span className="comment-sp" onClick={() => goback(reply)}>回复</span>
                {/* 如果有更多层级的回复，则递归渲染 */}
                {reply.replies && reply.replies.length >
                    0 && renderReplies(reply.replies)}
            </div>
        )) : null;
    };

    const [dianzan, setDianzan] = useState(list.flag || false)



    //点击心然后+1或减一
    const dianji = async () => {
        const newDianzan = !dianzan;
        // const newDianzanNum = newDianzan ? dianzanNum + 1 : dianzanNum - 1;
        // setDianzanNum(newDianzanNum);
        try {
            const res = await postAddlike({ id: list.id, flag: newDianzan, });

            if (res.data.code === 200) {
                setDianzan(newDianzan);
                // 确保 getdata 是一个有效的函数
                if (typeof getdata === 'function') {
                    getdata();
                } else {
                    console.error('getdata 不是一个有效的函数');
                }
            } else {
                console.error('服务器响应错误');
            }
        } catch (error) {
            console.error('点赞请求失败:', error);
        }
    };




    return (
        <>
            <div className="pl">
                <span>评论{comments.length}</span>
                <span>点赞和收藏 {list.like}</span>
            </div>

            {/* 显示评论 */}
            {
                loading ? <div>加载中...</div> :
                    comments.length === 0 ?
                        <div><span>暂无评论</span></div> :
                        <div className="pl2">
                            <List>
                                {comments.map((comment, index) => (
                                    <div key={comment._id} className="comment-item-container">

                                        <div className="comment-item">
                                            <span className="comment-author">{comment.user.phone}</span>
                                            <div className="comment-content">
                                                <span>{comment.content}</span>
                                                <span className="comment-time">{format(comment.time, 'yyyy-MM-dd HH:mm ')}</span>
                                                <span className='comment-sp' onClick={() => goback(comment)}>回复</span>
                                            </div>
                                        </div>
                                        {/* 只有当评论有回复时才渲染回复部分 */}
                                        {comment.replies && comment.replies.length > 0 && (
                                            <div className="nested-replies">
                                                {renderReplies(comment.replies)}  {/* 递归调用 */}
                                            </div>
                                        )}
                                    </div>
                                ))}

                            </List>
                            {/* <InfiniteScroll loadMore={loadMore} hasMore={hasMore} /> */}

                        </div>
            }

            {/* 输入框和提交 */}
            <div className="pl-input">
                <input
                    type="text"
                    className="ipt"
                    value={singular}
                    onKeyDown={dian}  // 按下回车提交评论
                    onChange={(e) => setSingular(e.target.value)}  // 更新评论内容
                    placeholder={`${name}` || "说点什么"}
                />
                {
                    dianzan == false ? <HeartOutline onClick={dianji} className="icon" />
                        : <img src={img1} onClick={dianji} style={{ width: "3.8rem", height: "3.8rem" }} alt="" />
                }

                {/* 点赞 */}
                <MessageOutline className="icon" />

                {/* 发送 */}
            </div>
        </>
    );
};

export default Singular;
